<template>
  <view class="page">
    <u-form :model="editForm" :rules="rules" labelWidth="auto" ref="uForm">
      <u-form-item label="联系人" prop="name" borderBottom>
        <u-input
          v-model="editForm.name"
          border="none"
          placeholder="请输入姓名"
          maxlength="20"
          inputAlign="right"
          fontSize="28rpx"
          :placeholderStyle="placeholderStyle"
        />
      </u-form-item>
      <u-form-item label="手机号" prop="mobile" borderBottom>
        <u-input
          v-model="editForm.mobile"
          border="none"
          placeholder="请输入手机号码"
          maxlength="11"
          inputAlign="right"
          fontSize="28rpx"
          :placeholderStyle="placeholderStyle"
        />
      </u-form-item>
      <u-form-item
        label="所在地区"
        prop="formatted_address"
        borderBottom
        @click="openCity"
      >
        <u-input
          v-model="editForm.formatted_address"
          disabled
          disabledColor="#ffffff"
          placeholder="请选择所在地区"
          inputAlign="right"
          fontSize="28rpx"
          :placeholderStyle="placeholderStyle"
          border="none"
        />
      </u-form-item>
      <u-form-item label="详细地址" prop="address" borderBottom @click="getAddress">
        <u-input
          v-model="editForm.address"
          border="none"
          disabled
          disabledColor="#ffffff"
          placeholder="请选择详细地址"
          maxlength="50"
          inputAlign="right"
          fontSize="28rpx"
          :placeholderStyle="placeholderStyle"
        />
      </u-form-item>
      <u-form-item label="设为默认" prop="default" borderBottom>
        <view style="display: flex; width: 100%; justify-content: flex-end">
          <u-switch
            v-model="editForm.default"
            active-value="1"
            inactive-value="0"
            active-color="#3BA199"
            inactive-color="#F6F6FB"
            size="22"
          />
        </view>
      </u-form-item>
    </u-form>

    <view class="btn">
      <view class="button" @click="handleSubmit()"> 完成</view>
    </view>
    <u-picker
      :show="cityShow"
      ref="uPicker"
      close-on-click-overlay
      :columns="[province, city, county]"
      :default-index="[provinceIndex, cityIndex, countyIndex]"
      @close="cityShow = false"
      @cancel="cityShow = false"
      @change="changeCity"
      @confirm="confirmCity"
    />
  </view>
</template>

<script>
import { myEditAddress, myCityList } from "@/request/myApi.js";
export default {
  data() {
    return {
      editForm: {
        name: "", // 姓名
        mobile: "", // 手机号
        default: "0", // 是否设置成默认地址
        //地区
        country: "", // 国家
        province: "", //省份
        city: "", // 城市
        citycode: "", // 城市代码
        district: "", // 县
        adcode: "", // 地区代码
        formatted_address: "", //详细地区
        //详情
        address: "", //详细地址
        address_name: "", // 地址名称
        address_full: "", // 完整地址名称
        latitude: "", // 纬度
        longitude: "", // 经度
      },
      rules: {
        name: {
          type: "string",
          required: true,
          message: "请填写昵称",
          trigger: ["blur", "change"],
        },
        mobile: [
          {
            type: "string",
            required: true,
            message: "请输入手机号码",
            trigger: ["blur", "change"],
          },
        ],
        formatted_address: {
          type: "string",
          required: true,
          message: "请选择所在地区",
          trigger: ["blur", "change"],
        },
        address: {
          type: "string",
          required: true,
          message: "请输入详细地址",
          trigger: ["blur", "change"],
        },
      },
      cityShow: false, // 所在地区弹窗
      cityList: [], // 所在地区列表
      provinceIndex: 0, // 省份下标
      cityIndex: 0, // 城市下标
      countyIndex: 0, // 区县下标
      placeholderStyle: {
        fontSize: "28rpx",
        color: "#D9D9D9",
      },
      manageType: "", // 操作
    };
  },
  computed: {
    province() {
      return this.cityList.map((i) => i.name);
    },
    city() {
      return this.cityList[this.provinceIndex].city.map((i) => i.name);
    },
    county() {
      return this.cityList[this.provinceIndex].city[this.cityIndex].area.map(
        (i) => i.name
      );
    },
  },
  onReady() {
    //兼容微信小程序，只能通过setRules方法设置。
    this.$refs.uForm.setRules(this.rules);
  },
  onLoad(e) {
    if (e.type === "edit") {
      this.editForm = JSON.parse(e.data);
    }
    this.manageType = e.type || "add";
    this.getCityList();
  },
  methods: {
    // 打开选择器
    openCity() {
      this.cityShow = true;
      if (this.manageType == "edit") {
        let { province, citycode, adcode } = this.editForm;
        this.provinceIndex = this.cityList.findIndex((i) => i.name == province);
        this.$refs.uPicker.setColumnValues(0, this.cityList);
        this.cityIndex = this.cityList[this.provinceIndex].city.findIndex(
          (i) => i.code == citycode
        );
        this.countyIndex = this.cityList[this.provinceIndex].city[
          this.cityIndex
        ].area.findIndex((i) => i.zip == adcode);
        console.log(this.provinceIndex, this.cityIndex, this.countyIndex);
        this.$forceUpdate();
      }
      uni.hideKeyboard();
    },
    // 获取收货地址
    getAddress() {
      uni.chooseLocation({
        latitude: this.editForm.latitude,
        longitude: this.editForm.longitude,
        success: (res) => {
          console.log(this.editForm);
          this.editForm.latitude = res.latitude;
          this.editForm.longitude = res.longitude;
          this.editForm.address = res.name;
        },
      });
    },
    // 获取城市列表
    getCityList() {
      myCityList().then((res) => {
        if (res.code == 1) {
          this.cityList = res.data;
        }
      });
    },
    // 改变地区
    changeCity({ columnIndex, index }) {
      if (columnIndex == 0) {
        this.provinceIndex = index;
      } else if (columnIndex == 1) {
        this.cityIndex = index;
      }
    },
    // 选择所在地区
    confirmCity({ indexs }) {
      let list = this.cityList;
      let [p, c, t] = indexs;
      this.editForm.country = "中国";
      this.editForm.province = list[p].name;
      this.editForm.city = list[p].city[c].name;
      this.editForm.citycode = list[p].city[c].code;
      this.editForm.adcode = list[p].city[c].area[t].zip;
      this.editForm.district = list[p].city[c].area[t].name;
      this.editForm.address_name = "";
      this.editForm.formatted_address =
        this.editForm.province + this.editForm.city + this.editForm.district;
      this.editForm.address_full = this.editForm.address_name + this.editForm.address;
      this.cityShow = false;
    },
    // 提交
    handleSubmit() {
      this.$refs.uForm.validate().then(() => {
        if (!/^1[3-9]\d{9}$/.test(this.editForm.mobile)) {
          uni.showToast({
            title: "手机格式不正确",
            icon: "none",
          });
          return;
        }
        let data = {
          data: this.editForm,
          type: this.manageType,
        };
        myEditAddress(data).then((res) => {
          if (res.code == 1) {
            uni.showToast({
              title: "保存成功",
              icon: "none",
              success: () => {
                setTimeout(() => {
                  this.$prePage().refreshList();
                  uni.navigateBack({ delta: 1 });
                }, 1500);
              },
            });
          }
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  padding: 20rpx;

  .btn {
    position: fixed;
    background-color: #fff;
    box-shadow: 0 0 8rpx rgba(0, 0, 0, 0.05);
    height: 126rpx;
    padding: 20rpx;
    bottom: 0;
    left: 0;
    right: 0;
    .button {
      width: 100%;
      height: 88rpx;
      text-align: center;
      line-height: 88rpx;
      color: $active-color;
      font-size: 28rpx;
      background-color: #cee7e5;
      border-radius: 100rpx;
      &:active {
        background-color: #b9e4e1;
      }
    }
  }
}
</style>
